/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-04-15
 * Time: 15:44
 */


class MyBlockingQueue{
    private String[] data = null;

    //队首
    private int head = 0;

    //队尾
    private int tail = 0;

    //元素个数
    private int size =0;

    public MyBlockingQueue(int capacity){
        data = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized(this){
            while(size >= data.length){
                //队伍满了，需要堵塞
                this.wait();
            }
            data[tail] = elem;
            tail++;
            if(tail >= data.length){
                tail = 0;
            }

            //成环的方式
            //tail = (tail + 1) % data.length;

            size++;
            //用来唤醒队列空时的阻塞
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized(this){
            //多循环条件
           while(size == 0){
               //队列空了，需要阻塞
               this.wait();
           }
           String ret = data[head];
           head++;
           if(head >= data.length){
               head = 0;
           }
           size--;
           //用来唤醒队列满时的阻塞
           this.notify();
           return ret;
        }
    }
}

public class demo7 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);

        Thread producer = new Thread(() -> {
            int n = 0;
            while(true){
                try {
                    queue.put(n + " ");
                    System.out.println("生产元素：" + n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() ->{
            while(true){
                String n = null;
                try {
                    n = queue.take();
                    System.out.println("消费元素：" + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
